<template>
  <div class="publish-container">
      <el-card class="box-card">
         <div slot="header" class="clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ $route.query.id ? '修改文章' : '发布文章' }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="text item">
          <el-form
            :model="article"
            :rules="formRules"
            label-width="60px"
            ref="publish-form"
          >
          <el-form-item label="标题" prop="title">
            <el-input v-model="article.title"></el-input>
          </el-form-item>
           <el-form-item label="内容" prop="content">
            <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
            <!-- <el-tiptap lang="zh" v-model="article.content" :extensions="extensions"></el-tiptap> -->
            <el-tiptap
            v-model="article.content"
            lang="zh"
            :extensions="extensions"
            height="350"
            placeholder="请输入文章内容"
          ></el-tiptap>
          </el-form-item>
           <el-form-item label="封面">
            <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
            </el-radio-group>
            <template v-if="article.cover.type > 0">
              <upload-cover
                :key="cover"
                v-for="(cover, index) in article.cover.type"
                v-model="article.cover.images[index]"
              />
          </template>
          </el-form-item>
          <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择">
            <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onPublish(false)">发布</el-button>
            <el-button @click="onPublish(true)">存入草稿</el-button>
          </el-form-item>
          </el-form>
      </div>
      </el-card>
  </div>
</template>

<script>
import UploadCover from './upload-cover.vue'
import 'element-tiptap/lib/index.css'
import { uploadImage } from '@/api/images'
import { getChannel, PublishArticle, GetArticleById, UpdateArticleById } from '@/api/article'
import {
  // 需要的 extensions
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  Image,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
  TextColor
} from 'element-tiptap'
export default {
  name: 'PublishIndex',
  data () {
    return {
      article: {
        title: '',
        content: '',
        cover: {
          type: 0,
          images: []
        },
        channel_id: null
      },
      formRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在 5 到 30 个字符', trigger: 'blur' }
        ],
        content: [
          {
            validator (rule, value, callback) {
              if (value === '<p></p>') {
                // 验证失败
                callback(new Error('请输入文章内容'))
              } else {
                // 验证通过
                callback()
              }
            }
          },
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '请选择文章频道' }
        ]
      },
      channels: [],
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline(), // 下划线
        new Italic(), // 斜体
        new Image({
          // 默认会把图片生成 base64 字符串和内容存储在一起，如果需要自定义图片上传
          uploadRequest (file) {
            // 如果接口要求 Content-Type 是 multipart/form-data，则请求体必须使用 FormData
            const fd = new FormData()
            fd.append('image', file)
            // 第1个 return 是返回 Promise 对象
            // 为什么？因为 axios 本身就是返回 Promise 对象
            return uploadImage(fd).then(res => {
              // 这个 return 是返回最后的结果
              return res.data.data.url
            })
          } // 图片的上传方法，返回一个 Promise<url>
        }),
        new Strike(), // 删除线
        new HorizontalRule(), // 华丽的分割线
        new ListItem(),
        new BulletList(), // 无序列表
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
        new TextColor()
      ]
    }
  },
  methods: {
    onPublish (draft) {
      this.$refs['publish-form'].validate((valid) => {
        if (valid) {
          const id = this.$route.query.id
          if (id) {
            UpdateArticleById(id, this.article, draft).then(res => {
              if (res.status === 201) {
                if (draft) {
                  this.$message.success('已保存到草稿箱！')
                } else {
                  this.$message.success('修改文章成功！')
                }
                this.$router.push('/article')
              } else {
                if (draft) {
                  this.$message.error('保存到草稿箱失败！')
                } else {
                  this.$message.error('修改文章失败！')
                }
              }
            })
          } else {
            PublishArticle(this.article, draft).then(res => {
              if (res.status === 201) {
                if (draft) {
                  this.$message.success('已保存到草稿箱！')
                } else {
                  this.$message.success('发布文章成功！')
                }
                this.$router.push('/article')
              } else {
                if (draft) {
                  this.$message.error('保存到草稿箱失败！')
                } else {
                  this.$message.error('发布文章失败！')
                }
              }
            })
          }
        } else {
          return false
        }
      })
    },
    loadChannerls () {
      getChannel().then(res => {
        this.channels = res.data.data.channels
      })
    },
    loadArticle (id) {
      GetArticleById(id).then(res => {
        this.article = res.data.data
      })
    },
    onUpdateCover (index, url) {
      this.article.cover.images[index] = url
    }
  },
  components: {
    'el-tiptap': ElementTiptap,
    UploadCover
  },
  props: {},
  computed: {},
  watch: {},
  created () {
    this.loadChannerls()
    if (this.$route.query.id) {
      this.loadArticle(this.$route.query.id)
    }
  },
  mounted () {
  }
}
</script>

<style scoped>
  .el-dialog{
    width: 20%;
  }
</style>
